package array.bisection;

/**
 * @Author: 海琳琦
 * @Date: 2021/12/13 11:53
 * 给定一个按照升序排列的整数数组 nums，和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
 *
 * 如果数组中不存在目标值 target，返回 [-1, -1]。
 *
 *示例 1：
 *
 * 输入：nums = [5,7,7,8,8,10], target = 8
 * 输出：[3,4]
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 */
public class Title34 {
    public static void main(String[] args) {
        int[] nums = {8,8,8,8,8,8};
        int[] result = searchRange(nums, 8);
        System.out.println(result[0]);
        System.out.println(result[1]);
    }

    private static int[] searchRange(int[] nums, int target) {
        int start = 0, end = nums.length-1;
        int middle, left, right;
        while(start<=end){
            middle = (start + end) / 2;
            if(nums[middle]<target){
                start = middle + 1;
            }else if(nums[middle]>target){
                end = middle - 1;
            }else{
                //查找左右边界 一个一个查速度慢
                while(nums[start]!=target){
                    start++;
                }
                left = start;
                while(nums[end]!=target){
                    end--;
                }
                right = end;
                return new int[]{left, right};
            }
        }
        return  new int[]{-1,-1};
    }

    /**
     * int[] result={-1,-1};
     * result[0] = searchRange1(nums,target, true);
     * result[1] = searchRange1(nums, target, false);
     * @param nums
     * @param target
     * @param startLeft
     * @return
     */
    private static int searchRange1(int[] nums, int target, boolean startLeft) {
        int start = 0, end = nums.length-1;
        int middle, result = -1;
        while(start<=end){
            middle = (start + end) / 2;
            if(nums[middle]<target){
                start = middle + 1;
            }else if(nums[middle]>target){
                end = middle - 1;
            }else{
                //查找左右边界
                result = middle;
                //先查左边
                if(startLeft){
                    end = result - 1;
                }else{
                    //第二次调用再查右边
                    start = result + 1;
                }
            }
        }
        return result;
    }

}
